import React from 'react'
// =====================================================================
import Encrypt from '@com/plugins/encrypt'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
import FormModal from '#cpt/temp/FormModal'
import SpecCode from '#tp/specCode'
// ===================================================================== global declare
const { $fn, $http, $Lazy } = window
// ===================================================================== $Lazy
const Page 				= $Lazy.load(()=>import('#tp/page/page-container'))
const message 			= $Lazy.file(()=>import('@antd/message'))
const $cache 			= $Lazy.file(()=>import('#private/cache-api'))
const $time 			= $Lazy.file(()=>import('@com/utils/time'))
const confirm 			= $Lazy.file(()=>import('@antd/confirm'))

const CodeInvalid		= $Lazy.state(()=>import('./cpt/code-invalid-modal'))
const ProjectInvalid 	= $Lazy.state(()=>import('./cpt/project-invalid-modal'))
const MoreProject 		= $Lazy.state(()=>import('./cpt/more-project-modal'))
const ThirdCode 		= $Lazy.state(()=>import('./cpt/third-code-modal'))
const ProjectImport		= $Lazy.state(()=>import('./cpt/project-import-modal'))
// ===================================================================== data
const BoolStatus = [{ name:'是', value: '1' }, { name:'否', value:'0' }]
const Prostatus = [{ name:'全部', value:'99' },{ name:'待审核', value:'0' },{ name:'已审核', value:'1' },{ name:'待保存', value:'-2' },{ name:'待录入', value:'-3' }]
const AuditStatus = [{ name:'待审核', value:'0' },{ name:'已审核', value:'1' },{ name:'待保存', value:'-2' },{ name:'待录入', value:'-3' }]
// ===================================================================== component
class Index extends React.Component{
	state={
		data:[],
		pag: {},
		selectedKeys:[],
		selectedRows:[],
		auditCount:{},	// 各状态总数据
		view_pic: 0,
		// 搜索表单列表
		forms: [
			{ label: '条码号',		name: 'spec_code' },
			{ label: '状态',		name: 'enabled',			type: 'select', 	value: '',	data:Prostatus,	onValue:()=> {
				this.setState({selectedKeys:[]})
			}},
			{ label: '标本箱号',		name: 'box_num_id',				type: 'select', 	onValue: ({rows})=>{this.model.box_num=rows?.name}},
			{ label: '第三方条码',	name: 'third_spec_code' },
			{ label: '录入时间',		names: ['start_at','end_at'], 	type:'date-range', name: 'jz-time',  onValue: () => {
				this.getAuditCount()
			}  },
			{ label: '医院名称',		name: 'hosp_id',				type: 'select', 	loading:true,	onValue: ({rows})=>{this.model.hosp_name=rows?.name}},
			{ label: '标签类型',		name: 'tag',	idStr:'code',	type: 'select', 	loading:true },
			{ label: '项目名称',		name: 'kind_id',				type: 'select' },
			{ label: '加做项目',		name: 'additional_kind',		type: 'select',		data:[{ name:'所有', value:'0' },{ name:'是', value:'1' }] },
			{ label:' ', 			tag: '仅显示有图',	name: 'view_pic',		type: 'checkbox', colon:false, onValue: ({value})=>{this.setState({view_pic:value})}},
		],
		// 客户变更
		formData:[
			{ label: '开始条码', 	name:'start_code',	half:true},
			{ label: '结束条码', 	name:'end_code',	half:true,	
				btn:{ label:'生成',	 onClick:value=>{this.generateCode()} }},
			{ label: '条码号', 		name:'spec_code', 	full:true, 		type:'textarea',	required:true },
			{ label: '医院名称', 	name:'hosp_id', 	full:true, 		type:'select',		required:true},
			{ label: '姓名', 		name:'name', 		full:true,		p:' ',				disabled:true },
			{ label: '用户名', 		name:'account', 	half:true,							required:true,	onBlur:(value)=>{this.getName(value)} },
			{ label: '密码', 		name:'password', 	half:true, 		type:'password',	required:true,	onBlur:(value)=>{this.getName(value)} },
		],
		doubleEntryEnabled: 0
	}
	query = {enabled:''}
	submit = {
		page_source: 'sp'
	}
	model = {}
	btn_power = { bindthirdspec:1,batchkindvalid:1,sepckindvalid:1,batchspecvalid:1,changehosp:1,batchaudit:1,auditkind:1,batchadd:1,addkind:1,importcaseinfo:1,importkind:1 }
	
	componentDidMount(){
		// 按钮添加权限 2022-07-05 17:15:24  --马婷 
		const { ban_btn } = $fn.local('permissions')
		if($fn.hasArray(ban_btn)){
			if(ban_btn.includes('specimen.bindthirdspec')){		// 绑定第三方条码
				this.btn_power.bindthirdspec = 0
			}
			if(ban_btn.includes('specimen.batchkindvalid')){		// 批量项目作废
				this.btn_power.batchkindvalid = 0
			}
			if(ban_btn.includes('specimen.sepckindvalid')){		// 项目作废
				this.btn_power.sepckindvalid = 0
			}
			if(ban_btn.includes('specimen.batchspecvalid')){		// 批量条码作废
				this.btn_power.batchspecvalid = 0
			}
			if(ban_btn.includes('specimen.changehosp')){		// 客户变更
				this.btn_power.changehosp = 0
			}
			if(ban_btn.includes('specimen.batchaudit')){		// 批量审核
				this.btn_power.batchaudit = 0
			}
			if(ban_btn.includes('specimen.auditkind')){		// 审核项目
				this.btn_power.auditkind = 0
			}
			if(ban_btn.includes('specimen.batchadd')){		// 批量加做
				this.btn_power.batchadd = 0
			}
			if(ban_btn.includes('specimen.addkind')){		// 录入项目
				this.btn_power.addkind = 0
			}
			if(ban_btn.includes('specimen.importcaseinfo')){		// 基本资料导入
				this.btn_power.importcaseinfo = 0
			}
			if(ban_btn.includes('specimen.importkind')){		// 项目导入
				this.btn_power.importkind = 0
			}
		}
		
		this.getSelect()
		this.onTime()
		$fn.fresh.on(()=>{
			this.fetch().then((data)=>{
				const { selectedRows } = this.state
				const arr = selectedRows.map(v=>{
					return v.index
				})
				let rows = []
				data.forEach((item,i)=>{
					arr.forEach((v)=>{
						if (v===i){rows.push(item)}
					})
				})
				this.setState({selectedRows:rows})
			})
		})
		
		// 双录入权限 2022-07-04 16:10:02  --马婷 
		const { ban_field } = $fn.local('permissions')
		if($fn.hasArray(ban_field)){
			if(!ban_field.includes('speckind.first') && !ban_field.includes('speckind.second')){
				this.permissions = 'double'
			}else if(ban_field.includes('speckind.first')&&!ban_field.includes('speckind.second')){
				this.permissions = 'second'
			}else if(ban_field.includes('speckind.second')&&!ban_field.includes('speckind.first')){
				this.permissions = 'first'
			}else {
				this.permissions = 0
			}
		}else{
			this.permissions = 'double'
		}
		this.getDoubleEntry()	// 是否展示双录入
	}
	
	componentWillUnmount(){
		$fn.fresh.remove()
	}
	
	onTime = reset => {
		 $time.then(f=>{
			const arr = f.duration['7']()
			this.resetModel = { start_at: arr[0], end_at: arr[1], 'jz-time':arr }
			this.model = $fn.copy(this.resetModel)
			this.getAuditCount() // 修改请求发起位置 [2021-8-13 7:02:05 ?F10: PM?] --伍智睿
			// this.fetch()		 /* 第一次进入页面不加载数据  2021-8-26  --马婷 */
		})
	}
	// 获取下拉数据
	getSelect = () => {
		const { forms,formData } = this.state
		
		$cache.then( async f => {
			// 标签
			$fn.setRow( forms, 'tag', await f.getDicCache({ code:69700 }) )
			// 医院
			const _data = await f.getCache({ api:'hospital' })
			$fn.setRows( [forms,formData], 'hosp_id',  _data)
			// 标本箱号
			$fn.setRow( forms, 'box_num_id', await f.getCache({ api:'box/select3', param:{limit:10000} }) )
			// 项目名称
			$fn.setRow( forms, 'kind_id', await f.getCache({ api: 'project_name' }))
			//
			this.setState({ forms,formData })
		})
	}

	// paging
	fetch = () => $fn.fetch.call(this,'specimen/itemlists',{isIndex:true})
	
	// 各状态总数
	getAuditCount = () => {
		// 增加时间参数 [2021-8-13 7:02:05 ?F10: PM?] --伍智睿
		const {start_at, end_at } = this.model
		$http.pull(this,'specimen/count',{dataName:'auditCount', param:{ start_at, end_at }} )
	}
	
	// 是否显示双录入按钮
	getDoubleEntry = () => {
		$http.submit(this,'spec-case-info/getDoubleEntryEnabled', { loading:false }).then((data)=>{
			this.setState({doubleEntryEnabled:data.enabled})
		})
	}
	
	// 根据账号获取姓名
	getName = (value)=>{
		if(value){
			const formValue = this.formRef.getValue(['account','password'])
			$http.submit(null, 'employee/getuserrealname', {param:{phone:formValue.account,password:formValue.password},loading:false }).then((data)=> {
				if(!$fn.hasArray(data)){
					if(data.length === 0){
						this.formRef.setValue({name:''})
					}else{
						this.formRef.setValue({name:data.real_name})
					}
				}
			})
		}
	}
	
	// 生成条码
	generateCode = () => {
		const {start_code, end_code} = this.formRef.getValue(['start_code','end_code'])
		if(start_code && (start_code.length === 12 || start_code.length === 14 )){
			if(start_code && end_code && +start_code > +end_code ){
				return message.then(f=>f.warning('开始条码必须小于结束条码'))
			}else{
				if(end_code.length === 12 || end_code.length === 14){
					const arr =[]
					for(var i = parseInt(start_code); i <= parseInt(end_code); i++){
						arr.push(i)
					}
					let {spec_code} = this.formRef.getValue(['spec_code'])					
					let specData = []
					if(spec_code){
						spec_code = spec_code.match(/\d{14}|\d{12}/g)
						spec_code.forEach(v=>{
							specData.push(parseInt(v))
						})
					}
					spec_code = Array.from(new Set([...specData, ...arr]))
					this.formRef.setValue({spec_code: spec_code.join('\r')})
				}
			}
		}else{
			return message.then(f=>f.warning('开始条码不正确'))
		}
	}
	// 解析条码
	getSpec = () => {
		let {spec_code} = this.formRef.getValue(['spec_code'])
		// spec_code = spec_code.replace(/\s+|，/g,',')
		// spec_code = spec_code.split(',')
		spec_code = spec_code.match(/\d{14}|\d{12}/g)
		this.submit.spec_code = Array.from(new Set(spec_code)).join(',')
	}
		
	// 表单
	cols = [
		{ title: '标本箱号', 	dataIndex: 'box_num',				...$fn.table.exp_num,	 },
		{ title: '医院名称', 	dataIndex: 'hosp_name', 			 width:200 },
		{ title: '条码号', 		dataIndex: 'spec_code',  			...SpecCode(),  			sorter:true },
		{ title: '采集时间', 	dataIndex: 'coll_time',  			...$fn.table.time,  		sorter:true },
		{ title: '采集类型', 	dataIndex: 'collect_type_name',  	width:100  },			 /* 添加采集类型 2021-8-11 --马婷 */
		{ title: '标本类型', 	dataIndex: 'spec_type_name', 		 width:150, },
		{ title: '项目状态', 	dataIndex: 'enabled', 			 	width:100,					render: text => $fn.getState(AuditStatus,text) },
		{ title: '加做项目', 	dataIndex: 'additional_kind', 		 ...$fn.table.status,		render: text => $fn.getState(BoolStatus,text) },
		{ title: '项目列表', 	dataIndex: 'kind_str', 				 width:250 },
		{ title: '录入时间', 	dataIndex: 'arrival_time',  		...$fn.table.time,			sorter:true, },
		{ title: '第三方来源', 	dataIndex: 'third_source_type_name', width:150 },
		{ title: '第三方条码', 	dataIndex: 'third_spec_code', 		 width:150 },
		{ title: '第三方医院', 	dataIndex: 'third_hosp_name', 		 width:150 },
	]
	
	// 操作按钮
	controls = () => {
		const { selectedRows, view_pic } = this.state
		const rows = selectedRows[selectedRows.length-1]
		const root = '/specimen-manage/info-entry/project-list/'
		const { bindthirdspec,batchkindvalid,sepckindvalid,batchspecvalid,changehosp,batchaudit,auditkind,batchadd,addkind,importcaseinfo,importkind } = this.btn_power
		return [
			// Controls.imports.call(this, 'specimen/import', { label: '项目导入' }),	// 增加项目导入 [2021-8-2 3:19:33 ?F10: PM?] --伍智睿
			importkind && Controls.click.call(this, '项目导入', ()=> {
				this.projectImportModal.open()
			}),   // 导入增加弹窗 2021-8-23 2:27:20 ?F10: PM? --伍智睿
			importcaseinfo && Controls.imports.call(this, 'spec-case-info/importUpdate', { label: '基本资料导入' }), // 增加基本资料导入 [2021-8-3 9:40:52 ?F10: AM?] --伍智睿
			addkind && Controls.click.call(this, '录入项目', ()=>{
				let path 
				if(rows && rows.enabled === '-3'){
					path = `${root}project-enter?isAudit=${0}&rows=${JSON.stringify(rows)}&view_pic=${view_pic}`
				}else {
					path = `${root}project-enter?isAudit=${0}&view_pic=${view_pic}`
				}
				$fn.pushRoot(this, path)
			},{code: 'F1',ghost:true} ),
			(+this.state.doubleEntryEnabled === 1 && this.permissions) 
				&& Controls.pushTo.call(this, '双录入', `double-entry?spec_code=${rows?rows.spec_code:''}&permissions=${this.permissions}` ),		// 新增双录入   --马婷
			batchadd && Controls.click.call(this, '批量加做', ()=>{
				const spec_codes = selectedRows.filter(v => v.enabled === '1')
				const spec_code = spec_codes.map(v => v.spec_code)
				$fn.pushRoot(this, `${root}project-additional?spec_codes=${spec_code}`)
			},{ghost:true}),
			auditkind && Controls.click.call(this, '审核项目', ()=>{
				if(rows && rows.enabled === '0'){
					$fn.pushRoot(this, `${root}project-enter?isAudit=${1}&rows=${JSON.stringify(rows)}&view_pic=${view_pic}`)
				}else {
					message.then(f=>f.error('请选择状态为 待审核 的项目', 1.5))
				}
			},{code: 'F2', isKeys:1,ghost:true} ),
			batchaudit && Controls.click.call(this, '批量审核', ()=>{
				const arr = selectedRows.map(v=>{
					return v.enabled
				})
				const notAudit = arr.every(v=>{
					return v === '0'
				})
				let spec_ids = []
				selectedRows.forEach((v, i)=> {
					spec_ids[i] = v.uuid
				})
				if(notAudit){
					confirm.then( f => {
						f({
							msg:'是否确认批量审核？',
							onOk: async close => {
								$http.submit(null,'specimen/batchaudit',{ param:{ spec_ids:spec_ids}, loadingText:`审核中`}).then(data=>{
									close()
									message.then(f=>f.success(`审核成功`))
									this.fetch().then(()=>{
										this.setState({selectedKeys:[],selectedRows:[]})
									})
								})
							}
						})
					})
				}else{
					message.then(f=>f.error('请选择状态为 待审核 的项目', 1.5))
				}
			},{ code: 'F3', isKeys:1}),
			changehosp && Controls.click.call(this, '客户变更', ()=>{ 
				const userData = $fn.getUser()
				const { empl_name, real_name } = userData
				const m = $fn.longSave('remember')
				if($fn.hasObject(m)){
					for(var i in m){ m[i] = Encrypt.decode(m[i]) }
				}
				this.formRef.setValue({account: empl_name, password: m?m.password:'', name:real_name })
				this.modal.open({formRef: this.formRef})
			},{code: 'F7',} ),
			batchspecvalid && Controls.click.call(this, '批量条码作废', () => { this.codeInvalidModal.open(selectedRows) } ),		/* 条码作废改为批量条码作废 2021-8-10  --马婷 */
			sepckindvalid && Controls.click.call(this, '项目作废', () => { 																// 项目作废
				if(rows.enabled === '1'){
					this.projectInvalidModal.open(rows)
				}else{
					message.then(f=>f.error('请选择审核成功的项目', 1.5))
				}
			}, { isKeys:1, } ),
			batchkindvalid && Controls.click.call(this, '批量项目作废', () => { this.moreProjectModal.open(selectedRows) }, { } ),						// 批量项目作废
			bindthirdspec && Controls.click.call(this, '绑定第三方条码', () => { this.thirdCodeModal.open(selectedRows) } ),			/* 修改绑定第三方条码可批量操作 2021-8-12 11:41:05 --马婷 */
		]
	}
	
	render(){
		const {  auditCount } = this.state
		return (
			<>
				<Page title='项目清单' controls={this.controls()} >
					{/* 搜索 */}
					{ SearchForm.call(this, {timeStr:'7'}) }
					{/* 表格 */}
					{ Table.call(this, { sort:true, isIndex:true,
						suffix: ()=>(
							<>
								<span className='mr15'><span>已审核 :	</span> <b className='f14 c0'>{auditCount.audit_pass}</b></span>
								<span className='mr15'><span>待审核 :	</span> <b className='f14 c0'>{auditCount.audit_audit}</b></span>
								<span className='mr15'><span>待保存 :	</span> <b className='f14 c0'>{auditCount.audit_save}</b></span>
								<span className='mr15'><span>待录入 :	</span> <b className='f14 c0'>{auditCount.audit_add}</b></span>
							</>
						)
					}) }
				
				</Page>
				{/* 客户变更 */}
				{FormModal.call(this,{ title:'客户变更', labelWidth:'s5', width:800, api:'specimen/changehosp',enter:false,onOk:this.getSpec})}
				{/* 条码作废 */}
				<CodeInvalid onRef={ref=>this.codeInvalidModal=ref} onRefresh={()=>{
					this.fetch()
					this.setState({selectedKeys:[],selectedRows:[]})
				}} />
				{/* 项目作废 */}
				<ProjectInvalid onRef={ref=>this.projectInvalidModal=ref} onRefresh={()=> {
					this.fetch()
					this.setState({selectedKeys:[],selectedRows:[]})
				}} />
				{/* 批量项目作废 */}
				<MoreProject onRef={ref=>this.moreProjectModal=ref} onRefresh={()=>{
					this.fetch()
					this.setState({selectedKeys:[],selectedRows:[]})
				}} />
				{/* 绑定第三方条码 */}
				<ThirdCode onRef={ref=>this.thirdCodeModal=ref} onRefresh={()=>{
					this.fetch()
					this.setState({selectedKeys:[],selectedRows:[]})
				}} />
				{/* 项目导入 */}
				<ProjectImport onRef={ref=>this.projectImportModal=ref} onRefresh={()=>{
					this.fetch()
				}}/>
			</>
		)
	}
}
export default Index